//
//  HJVistCardControlle.m
//  newOcWeibo
//
//  Created by heJing on 15/7/26.
//  Copyright © 2015年 heima. All rights reserved.
//

#import "HJVistCardControlle.h"
#import <CoreImage/CoreImage.h>

@interface HJVistCardControlle ()
@property (weak, nonatomic) IBOutlet UIImageView *icon;

@end

@implementation HJVistCardControlle

- (void)viewDidLoad {
    [super viewDidLoad];

    //1. 创建滤镜对象
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    
    //2. 还原滤镜初始化属性
    [filter setDefaults];
    
    //3. 将需要生成二维码的数据转换成二进制
    NSData *data = [@"王八蛋" dataUsingEncoding:NSUTF8StringEncoding];
    
    //4. 给二维码滤镜设置数据
    [filter setValue:data forKeyPath:@"inputMessage"];
    
    //5. 获取滤镜生成的图片
    CIImage *ciImage = [filter outputImage];
    
    UIImage *bgImg = [self createNonInterpolatedUIImageFormCIImage:ciImage withSize:120];
    
    // 添加二维码logo图片在中间
    UIImage *newImg = [self creatNewImgWithBg:bgImg icon:[UIImage imageNamed:@"navigationbar_friendsearch_highlighted"]];
    
    //6. 设置图片到控件上
    self.icon.image = newImg;


}

-(UIImage *)creatNewImgWithBg:(UIImage *)bgImg icon:(UIImage *)iconLogo
{
    // 1.开启上下文
    UIGraphicsBeginImageContext(bgImg.size);
    
    // 2. 绘制背景
    [bgImg drawInRect:CGRectMake(0, 0, bgImg.size.width, bgImg.size.height)];
    
    // 3.绘制图标
    CGFloat iconW = 30;
    CGFloat iconH = 30;
    CGFloat iconX = (bgImg.size.width - iconW) * 0.5;
    CGFloat iconY = (bgImg.size.height - iconH) * 0.5;
    [iconLogo drawInRect:CGRectMake(iconX, iconY, iconW, iconH)];
    
    // 4.取出绘制好的图片
    UIImage *newImg = UIGraphicsGetImageFromCurrentImageContext();

    // 5.关闭上下文
    UIGraphicsEndImageContext();
    
    return newImg;
}

/**
 *  根据CIImage生成指定大小的UIImage, 并且是高清的img
 *
 *  @param image CIImage
 *  @param size  图片宽度
 */
- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size
{
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    // 1.创建bitmap;
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    // 2.保存bitmap到图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    return [UIImage imageWithCGImage:scaledImage];
}


@end
